import json
from frame_work.logger import Logger
from frame_work.login import PcLogin
from frame_work.util import check_tid, assert_result_dict, get_sql_info
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work import menu_list

logger = Logger(__name__).get_logger()


class ApplyAudit(object):
    def __init__(self, tid):
        self.tid = tid
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    @staticmethod
    def get_session(seller_uname):
        """
        返回登录session
        :param seller_uname:
        :return:
        """
        login = PcLogin(seller_uname)
        login.pc_login()
        return login.get_session()

    def get_all_audited_user(self):
        """
        获取所有待审核的用户
        """
        users = []
        statement = """SELECT
                        t.uname,
                        ta.uid
                    FROM
                        sk_try t,
                        sk_try_apply ta
                    WHERE
                        t.tid = ta.tid
                    AND t.tid = %s
                    AND ta.state = 1"""
        params = (self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "获取活动的uid申请集合"
        })
        if len(value):
            for obj in value:
                uid = obj.get("uid")
                users.append(uid)
            return {"uname": value[0].get("uname"), "users": users}
        else:
            logger.debug('该活动没有待审核的用户')

    def audit(self, uname):
        """
        审核单个试客
        :param uname:
        :return:
        """
        statement = """SELECT
                        t.uname,ta.uid
                    FROM
                        sk_try t
                    INNER JOIN sk_try_apply ta ON t.tid = ta.tid
                    WHERE
                        ta.uname = %s
                    AND ta.tid = %s"""
        params = (uname, self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "获取活动的试客申请信息"
        })
        yaml_data = self.yaml.get_data('audit_apply')
        uid = value[0].get("uid")
        seller_uname = value[0].get("uname")
        yaml_data.get('data').update({'tid': self.tid, 'uid': uid})
        session = ApplyAudit.get_session(seller_uname)
        response = session.post(
            yaml_data.get('url'),
            data=yaml_data.get('data'),
            headers=yaml_data.get('header')).text
        # promote = response.encode('utf-8').decode('unicode_escape')
        assert_result_dict(response, '审核' + uname + '的申请资格')

    def audit_all(self):
        """
        一键审核通过所有用户的申请
        :return:
        """
        yaml_data = self.yaml.get_data('audit_all_apply')
        user_objs = self.get_all_audited_user()
        uids = user_objs.get("users")
        seller_uname = user_objs.get('uname')
        yaml_data.get('data').update({'tid': self.tid,
                                      'uids[]': uids,
                                      'link_url': yaml_data.get('data')['link_url'] + '/' + str(self.tid) + '?key=&search_type=0'
                                      })
        session = ApplyAudit.get_session(seller_uname)
        response = session.post(
            yaml_data.get('url'),
            data=yaml_data.get('data'),
            headers=yaml_data.get('header'))
        text = response.text
        if '!DOCTYPE html' in text:
            logger.info('没有待审核的用户')
        else:
            # promote = text.encode('utf-8').decode('unicode_escape')
            result = json.loads(text)['result']
            if result == 1:
                logger.info('成功审核所有待审核的试客资格')
            else:
                logger.info('审核失败，请找原因')


def main():
    while True:
        # 显示功能菜单
        menu_list.apply_audit_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            audit_obj = ApplyAudit(tid)
            if choise == '1':
                buyer_name = input(u'请输入试客名称: ')
                audit_obj.audit(buyer_name)
            elif choise == '2':
                audit_obj.audit_all()
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == '__main__':
    main()
